package com.yexs.wechat.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.yexs.wechat.pojo.AccessToken;
import com.yexs.wechat.pojo.JsapiTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: 定时获取微信access_token的线程
 * @Author: yexs
 * @CreateDate: 2018/5/25 17:34
 * @Version: 1.0
 */
public class TokenThread implements Runnable {
    private static Logger log = LoggerFactory.getLogger(TokenThread.class);
    private AccessToken accessToken = null;
    private JsapiTicket jsapiTicket = null;

    @Override
    public void run() {
        while (true) {
            try {
                accessToken = CommonUtil.accessToken = getNewToken(Constant.appID, Constant.appSecret);
                jsapiTicket = CommonUtil.jsapiTicket = getJsapiTicket(Constant.appID, Constant.appSecret);
                if (null != accessToken) {
                    //调用存储到数据库
//                    TokenUtil.saveToken(accessToken);
                    log.info("获取access_token成功，有效时长{}秒 token:{}", accessToken.getExpiresIn(), accessToken.getAccessToken());
                    log.info("获取jsapiTicket成功，有效时长{}秒 ticket:{}", jsapiTicket.getExpiresIn(), jsapiTicket.getTicket());
                    // 休眠7000秒(微信返回token的有效期是7200s)
                    Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
                } else {
                    // 如果access_token为null，60秒后再获取
                    Thread.sleep(60 * 1000);
                }
            } catch (InterruptedException e) {
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e1) {
                    log.error("{}", e1);
                }
                log.error("{}", e);
            }
        }
    }

    /**
     * 获取接口访问凭证
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public AccessToken getNewToken(String appid, String appsecret) {
        AccessToken accessToken = null;
        String requestUrl = Constant.getTokenURL();
        // 发起GET请求获取凭证
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

    /**
     * 获取js临时票据
     *
     * @param appid
     * @param appsecret
     * @return
     */
    private JsapiTicket getJsapiTicket(String appid, String appsecret) {
        JsapiTicket jsapiTicket = null;
        String requestUrl = Constant.getJsapiTicketURL();
        // 发起GET请求获取凭证
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                jsapiTicket = new JsapiTicket();
                jsapiTicket.setErrCode(jsonObject.getInteger("errcode"));
                jsapiTicket.setExpiresIn(jsonObject.getInteger("expires_in"));
                jsapiTicket.setErrMsg(jsonObject.getString("errmsg"));
                jsapiTicket.setTicket(jsonObject.getString("ticket"));
            } catch (JSONException e) {
                jsapiTicket = null;
                // 获取token失败
                log.error("获取js 临时票据失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return jsapiTicket;
    }

}
